﻿using System.Drawing;
using System.IO;
using System.Net;
using Newtonsoft.Json;

namespace Hourglass.Qrobot.Http
{
    public static class HttpExtension
    {
        public static string GetStringContent(this WebResponse response, bool dispose = true)
        {
            var content = string.Empty;
            var stream = response.GetResponseStream();
            if (stream != null)
            {
                var reader = new StreamReader(stream);
                content = reader.ReadToEnd();
                if (dispose)
                {
                    reader.Dispose();
                    stream.Dispose();
                }
            }
            if(dispose) response.Dispose();

            return content;
        }

        public static Image GetImage(this WebResponse response, bool dispose = true)
        {
            Image image = null;
            var stream = response.GetResponseStream();
            if (stream != null)
            {
                image = Image.FromStream(stream);

                if (dispose) stream.Dispose();
            }
            if (dispose) response.Dispose();

            return image;
        }

        public static T GetJsonModel<T>(this WebResponse response, bool dispose = true)
        {
            var content = GetStringContent(response, dispose);
            if (string.IsNullOrEmpty(content)) return default(T);
            return JsonConvert.DeserializeObject<T>(content);
        }

        public static WebResponse CookieMerge(this WebResponse response, CookieContainer cookieContainer)
        {
            var httpResponse = response as HttpWebResponse;
            if (httpResponse != null)
            {
                cookieContainer.Add(httpResponse.Cookies);
            }
            return response;
        }

        public static void ApplyV1Referer(this HttpRequestHandler handler, string refererV1)
        {
            handler.Referer = string.Format(QrobotConsts.URL_Referer1, refererV1);
        }

        public static void ApplyV2Referer(this HttpRequestHandler handler, string refererV2)
        {
            handler.Referer = string.Format(QrobotConsts.URL_Referer2, refererV2);
        }

        public static void ApplyV1Referer(this HttpRequestHandler handler, QQContext context)
        {
            handler.Referer = string.Format(QrobotConsts.URL_Referer1, context.Config.RefererV1);
        }

        public static void ApplyV2Referer(this HttpRequestHandler handler, QQContext context)
        {
            handler.Referer = string.Format(QrobotConsts.URL_Referer2, context.Config.RefererV2);
        }
    }
}
